﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OL_OperationLogInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters { get; set; }
        public Base_InterfaceOption queryOption { get; set; }
        //public Base_InterfaceOption insertOption { get; set; }
        //public Base_InterfaceOption upDateOption { get; set; }
        //public Base_InterfaceOption deleteOption { get; set; }

        public List<OL_LogTable> RowList { get; set; }
        public List<OL_OperationLog> LogList { get; set; }
        public OL_OperationLogInterfaceBusiness()
        {
            this.InterfaceName = "OL操作日志";
            //获取字段的映射关系
            tableField = GetMapField("getFilterRows");
            //索引字段
            Keys = GetKeys("getFilterRows");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            this.ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            this.SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            //this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            //this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            //this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //查询日志的参数
            queryEventArgs.Page.WorksheetId = RowList[0].workSheetId;
            queryEventArgs.Page.RowId = RowList[0].rowid;
            queryEventArgs.Page.LastMark = RowList[0].utime.ToDateTime().AddDays(1).ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();


            //单个工作表是否查询完成
            if (queryEventArgs.Success)
            {
                //获取日志信息
                var log = queryEventArgs.Result["data"].ToObject<OL_OperationLog>();
                if (!log.logs.IsNullOrEmpty() && log.logs.Count > 0) this.LogList.Add(log);
                //queryEventArgs.Rows.Add(queryEventArgs.Result["data"]);
                //获取总页数
                //queryEventArgs.Page.Total = queryEventArgs.Rows.Count;
                //移除第一行，继续查询下一行
                RowList.RemoveAt(0);
                //if (queryEventArgs.Result["data"]["rows"].ToList().Count < queryEventArgs.Page.PageSize) 
                //判断所有表是否查询完成
                if (RowList.IsNullOrEmpty() || RowList.Count == 0) queryEventArgs.Page.Complete = true;

            }


        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //List<OL_OperationLog> rows = new List<OL_OperationLog>();
            this.LogList = new List<OL_OperationLog>();
            try
            {
                //获取需要备份的所有表的每一行
                OL_LogTableInterfaceBusiness oL_LogTableInterface = new OL_LogTableInterfaceBusiness();
                RowList = await oL_LogTableInterface.ExecuteInterface();
                //获取需要备份的所有表ID
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var tableList = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='OneLink_LogTable'");
                if (RowList.Count > 0)
                {
                    //执行查询
                    await QueryAsync<OL_OperationLog>(queryOption, tableField, SqlDb);

                    if (this.LogList.Count > 0)
                    {
                        //日志
                        List<SD_OL_OperationLog> OperationLogList = new List<SD_OL_OperationLog>();
                        List<SD_OL_OperationLogEntiy> OperationLogEntiyList = new List<SD_OL_OperationLogEntiy>();
                        //循环每一行
                        foreach (var row in this.LogList)
                        {
                            //循环每一行的每一条日志
                            foreach (var log in row.logs)
                            {
                                SD_OL_OperationLog head = new SD_OL_OperationLog();
                                head.accountId = log.opeartorInfo.accountId;
                                head.fullname = log.opeartorInfo.fullname;
                                head.avatar = log.opeartorInfo.avatar;
                                head.isPortal = log.opeartorInfo.isPortal;
                                head.status = log.opeartorInfo.status;
                                var t = tableList.Where(x => x.Value == log.operatContent.worksheetId);
                                head.worksheetName = !t.IsNullOrEmpty() && t.Count() > 0 ? t.First().Describe : "";
                                head.worksheetId = log.operatContent.worksheetId;
                                head.objectId = log.operatContent.objectId;
                                head.uniqueId = log.operatContent.uniqueId;
                                head.objectType = log.operatContent.objectType;
                                head.type = log.operatContent.type;
                                head.requestType = log.operatContent.requestType;
                                head.createTime = log.operatContent.createTime;
                                head.id = (head.uniqueId + head.objectId + head.worksheetId).ToMD5String();
                                OperationLogList.Add(head);
                                //循环每一条日志的每一操作记录
                                if (head.id== "1cecacc4aec425051501e6918d8fe3ef" || head.id == "25f07467d71d2acb3d126f4913595d5d" || head.id == "38f028b548aa495944a0450b8023add0" || head.id == "df94a19d35c927f45dfa17cb5633e1af")
                                {
                                    var ww = "";
                                }
                                if (!log.operatContent.logData.IsNullOrEmpty() && log.operatContent.logData.Count>0)
                                {
                                    foreach (var item1 in log.operatContent.logData)
                                    {
                                        SD_OL_OperationLogEntiy entiy = new SD_OL_OperationLogEntiy();
                                        entiy.hId = head.id;
                                        entiy.name = item1.name;
                                        entiy.editType = item1.editType;
                                        entiy.type = item1.type;
                                        entiy.oldValue = item1.oldValue;
                                        entiy.oldText = item1.oldText;
                                        entiy.newValue = item1.newValue;
                                        entiy.newText = item1.newText;
                                        entiy.id = (item1.id + entiy.hId).ToMD5String();
                                        entiy.createTime = head.createTime;
                                        entiy.worksheetId = head.worksheetId;
                                        OperationLogEntiyList.Add(entiy);
                                    }
                                }
                                else
                                {
                                    SD_OL_OperationLogEntiy entiy = new SD_OL_OperationLogEntiy();
                                    entiy.hId = head.id;
                                    entiy.newValue = "创建/取消了记录";
                                    entiy.id = entiy.hId;
                                    entiy.createTime = head.createTime;
                                    entiy.worksheetId = head.worksheetId;
                                    OperationLogEntiyList.Add(entiy);

                                }

                            }
                        }
                        var t1 = OperationLogList.GroupBy(x => x.id).Where(x => x.Count() > 1);
                        var t2 = OperationLogEntiyList.GroupBy(x => x.id).Where(x => x.Count() > 1);
                        //更新表头
                        SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys.Where(x => x.TField == "head").ToList());
                        sqlDBInterface.Count = 5000;
                        OperationLogList.GroupBy(x => x.worksheetId).ForEach(item1 =>
                        {
                            var firstTime = item1.OrderBy(x => x.createTime).First().createTime;
                            sqlDBInterface.ExecuteInterface<SD_OL_OperationLog>(item1.ToList(), "SD_OL_OperationLog", $"WHERE createTime >= '{firstTime}' AND worksheetId='{item1.First().worksheetId}'", false, false);


                        });


                        //更新表身
                        OperationLogEntiyList.GroupBy(x => x.worksheetId).ForEach(item1 =>
                        {
                            var firstTime1 = item1.OrderBy(x => x.createTime).First().createTime;
                            sqlDBInterface.Keys = Keys.Where(x => x.TField == "entiy").ToList();
                            sqlDBInterface.ExecuteInterface<SD_OL_OperationLogEntiy>(item1.ToList(), "SD_OL_OperationLogEntiy", $"WHERE createTime >= '{firstTime1}' AND worksheetId='{item1.First().worksheetId}'", false, false);
                        });

                    }
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row_Update<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }
        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
